package com.carepad.action;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.carepad.entity.Users;
import com.carepad.entity.mapper.EnJaDate;
import com.carepad.entity.mapper.SelectClient;
import com.carepad.exception.SessionNotExist;
import com.carepad.service.SelectClientService;
import com.carepad.util.DateConverterEnJa;
import com.carepad.util.SessionKey;
import com.opensymphony.xwork2.ActionSupport;

public abstract class AbstractAction extends ActionSupport implements
		SessionAware, ServletResponseAware, ServletRequestAware {

	private static final long serialVersionUID = 1L;
	public static final Integer DEFAULT_HEADER_KEY = -1;
	public static final String DEFAULT_HEADER_TEXT = "Invalid";
	
	public static final String VITAL_INPUT = "バイタル(定期)";
	public static final String BLOOD_PRESSURE_HIGH = "血圧（上）";
	public static final String BLOOD_PRESSURE_LOW = "血圧（下）";
	public static final String PULSE_RATE = "脈拍";
	public static final String BODY_TEMPERATURE = "体温";


	public enum STATUS {
		SUCCESS, FAILURE, NOT_FOUND, SERVER_ERROR, DB_ERROR
	}

	private static Logger logger = Logger.getLogger(AbstractAction.class);
	private static final String SESSION_NOT_EXIST = "Session doesn't exist";
	private Map<SessionKey, Object> session = null;
	private SelectClient patientName;

	protected static HttpServletResponse servletResponse;
	protected static HttpServletRequest servletRequest;

	private int x;
	private int y;

	protected STATUS status;

	@Qualifier("selectClientService")
	@Autowired
	protected SelectClientService selectClientService;

	public String alwaysSuccess() {
		return SUCCESS;
	}

	public String getSessionId() {
		return servletRequest.getSession().getId().toString();
	}

	public void addSessionUserVariable(Users user) throws SessionNotExist {
		// System.out.println(servletRequest.getSession().getId());
		if (session != null) {
			session.put(SessionKey.SESSION_USER, user);
		} else {
			logger.error(SESSION_NOT_EXIST);
			throw new SessionNotExist(SESSION_NOT_EXIST);
		}
	}

	public Users getSessionUserVariable() throws SessionNotExist {
		if (session != null) {
			if (session.containsKey(SessionKey.SESSION_USER)) {
				return (Users) session.get(SessionKey.SESSION_USER);
			} else {
				throw new SessionNotExist(SESSION_NOT_EXIST);
			}
		} else {
			logger.error(SESSION_NOT_EXIST);
			throw new SessionNotExist(SESSION_NOT_EXIST);
		}
	}

	public void removeSessionVariable(SessionKey key) throws SessionNotExist {
		if (session != null) {
			if (session.containsKey(key)) {
				session.remove(key);
			}
		} else {
			logger.error(SESSION_NOT_EXIST);
			throw new SessionNotExist(SESSION_NOT_EXIST);
		}
	}

	public boolean verifySessionUser() throws SessionNotExist {
		if (session != null) {
			return session.containsKey(SessionKey.SESSION_USER);
		} else {
			logger.error(SESSION_NOT_EXIST);
			throw new SessionNotExist(SESSION_NOT_EXIST);
		}
	}

	/*
	 * SelectClient patient ,SessionKey.CURRENT_PATIENT
	 */
	public SessionKey getSessionKey(Object obj) {

		SessionKey key = null;

		if (obj instanceof SelectClient) {
			key = SessionKey.CURRENT_PATIENT;

		} else if (obj instanceof Users) {
			key = SessionKey.SESSION_USER;

		} else if (obj instanceof EnJaDate) {
			key = SessionKey.IMPLEMENTATION_DATE;
		}

		return key;
	}

	public void addSessionVariable(Object obj) throws SessionNotExist {
		if (session != null) {

			if (session.containsKey(getSessionKey(obj))) {
				removeSessionVariable(getSessionKey(obj));
			}
			session.put(getSessionKey(obj), obj);

		} else {
			logger.error(SESSION_NOT_EXIST);
			throw new SessionNotExist(SESSION_NOT_EXIST);
		}
	}

	public Object getSessionVariable(SessionKey key) throws SessionNotExist {
		if (session != null) {
			if (session.containsKey(key)) {
				return session.get(key);
			} else {
				return null;
			}
		} else {
			logger.error(SESSION_NOT_EXIST);
			throw new SessionNotExist(SESSION_NOT_EXIST);
		}
	}

	public boolean verifySessionPatient() throws SessionNotExist {
		if (session != null) {
			return session.containsKey(SessionKey.CURRENT_PATIENT);
		} else {
			logger.error(SESSION_NOT_EXIST);
			throw new SessionNotExist(SESSION_NOT_EXIST);
		}
	}

	public EnJaDate getSessionImplementationDate() throws SessionNotExist {
		return (EnJaDate) getSessionVariable(SessionKey.IMPLEMENTATION_DATE);
	}

	public SelectClient getSessionPatient() throws SessionNotExist {
		return (SelectClient) getSessionVariable(SessionKey.CURRENT_PATIENT);
	}

	@Override
	@SuppressWarnings("unchecked")
	public void setSession(@SuppressWarnings("rawtypes") Map session) {
		this.session = session;
	}

	public STATUS getStatus() {
		return status;
	}

	public void setStatus(STATUS status) {
		this.status = status;
	}

	public boolean isLogin() {
		try {
			Users user = (Users) session.get(SessionKey.SESSION_USER);
			if (user != null) {
				return true;
			}
			return false;
		} catch (Exception e) {
			return false;
		}
	}

	public boolean isAdmin() {
		try {
			// Users user = (Users)session.get(SessionKey.SESSION_USER);
			/*
			 * if(user != null &&
			 * user.getUserType().equalsIgnoreCase(UserType.ADMIN.getType())){
			 * return true; }
			 */
			return false;
		} catch (Exception e) {
			return false;
		}
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	@Override
	public void setServletResponse(HttpServletResponse servletResponse) {
		AbstractAction.servletResponse = servletResponse;
	}

	@Override
	public void setServletRequest(HttpServletRequest servletRequest) {
		AbstractAction.servletRequest = servletRequest;
	}

	public static void setCookie(String name, String value) {

		try {

			String cval = getCookie(name);

			if (cval == null) {

				Cookie cookie = new Cookie(name, value);
				cookie.setMaxAge(60 * 60 * 24 * 7);
				cookie.setPath("/");
				servletResponse.addCookie(cookie);

			} else if (!cval.equals(value)) {

				for (Cookie c : servletRequest.getCookies()) {
					if (c.getName().equals(name)) {
						c.setValue(value);
						c.setMaxAge(60 * 60 * 24 * 7);
						c.setPath("/");
						servletResponse.addCookie(c);
					}
				}

			} else {

				return;

			}

		} catch (Exception e) {
			logger.log(Level.INFO, "message", e);
		}
	}

	public static String getCookie(String cookieName) {

		String value = null;

		try {

			for (Cookie c : servletRequest.getCookies()) {
				if (c.getName().equals(cookieName)) {
					value = c.getValue();
				}
			}

			return value;

		} catch (Exception e) {
			logger.log(Level.INFO, "message", e);
		}

		return value;
	}

	public static void deleteCookie(String cookieName) {

		for (Cookie c : servletRequest.getCookies()) {
			if (c.getName().equals(cookieName)) {
				c.setMaxAge(0);
				c.setValue(null);
				c.setPath("/");
				servletResponse.addCookie(c);
			}
		}
	}

	public void deleteAllCookies() {
		for (Cookie c : servletRequest.getCookies()) {
			c.setMaxAge(0);
			c.setValue(null);
			c.setPath("/");
			servletResponse.addCookie(c);
		}
	}

	public SelectClient getPatientByUid(String uid) {
		return selectClientService.findSelectClientPatientNameByUid(Integer
				.parseInt(uid));

	}

	public SelectClient getPatientName() {
		return patientName;
	}

	public void setPatientName(SelectClient patientName) {
		this.patientName = patientName;
	}

	@SuppressWarnings("deprecation")
	public String setImplementationDate(String getImplDate)
			throws ParseException {

		if (getImplDate == null || getImplDate.equals("SetByCookie")) {

			EnJaDate ejDate = getSessionImplementationDate();
			Date impldatetemp = new Date();
			String jadate = null;

			if (ejDate == null) {
				String implementationDate = getCookie("IMPLDATE");

				if (implementationDate != null) {

					SimpleDateFormat formatter = new SimpleDateFormat(
							"yyyy/MM/dd");
					impldatetemp = formatter.parse(implementationDate);
				} else {

					impldatetemp = new Date();

					int year = impldatetemp.getYear() + 1900;
					int month = impldatetemp.getMonth() + 1;
					int day = impldatetemp.getDate();

					StringBuilder sb = new StringBuilder();

					sb.append(year + "/" + month + "/" + day);

					setCookie("IMPLDATE", sb.toString());
				}

				jadate = DateConverterEnJa.EnDatetoJa(impldatetemp);

				EnJaDate ejDatetemp = new EnJaDate();

				ejDatetemp.setJaDate(jadate);
				ejDatetemp.setEnDate(impldatetemp);
				addSessionVariable(ejDatetemp);
			}

		} else {

			EnJaDate ejDatetemp = new EnJaDate();

			ejDatetemp.setJaDate(getImplDate);
			Date enDate = DateConverterEnJa.JaDatetoEnDate(getImplDate);
			ejDatetemp.setEnDate(enDate);

			int year = enDate.getYear() + 1900;
			int month = enDate.getMonth() + 1;
			int day = enDate.getDate();

			StringBuilder sb = new StringBuilder();

			sb.append(year + "/" + month + "/" + day);

			setCookie("IMPLDATE", sb.toString());

			addSessionVariable(ejDatetemp);
		}
		return SUCCESS;
	}
}
